package messageMeClient.view;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JScrollPane;

import messageMeTransfer.connection.ClientConnection;
import messageMeTransfer.packages.CommandPackage;
import messageMeTransfer.utilities.PackageWrapper;
import messageMeUtility.commands.CommandRegister;
import messageMeUtility.commands.CommandSendMessage;
import messageMeUtility.messages.TextMessage;
import messageMeUtility.user.StandardUser;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MainForm {

	public JFrame frame;
	private JTextArea textOutputArea = null;
	private JTextArea textInputArea = null;

	ClientConnection connection = null;
	PackageWrapper packageWrapper = null;

	public MainForm(ClientConnection connection, PackageWrapper wrapper) {
		this.connection = connection;
		this.packageWrapper = wrapper;
		this.initialize();
	}

	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 724, 505);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		this.textOutputArea = new JTextArea();
		this.textOutputArea.setBounds(10, 11, 688, 362);
		frame.getContentPane().add(textOutputArea);

		JButton btnNewButton = new JButton("Send");
		btnNewButton.addActionListener(this.getSendListener());
		btnNewButton.setBounds(562, 384, 136, 72);
		frame.getContentPane().add(btnNewButton);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 383, 544, 73);
		frame.getContentPane().add(scrollPane);

		this.textInputArea = new JTextArea();
		scrollPane.setViewportView(textInputArea);
	}

	public void appendText(String text) {
		this.textOutputArea.append(text + "\n");
	}

	private ActionListener getSendListener() {
		return new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MainForm.this.sendPackage();
			}
		};
	}

	private void sendPackage() {

		StandardUser sender = new StandardUser("Kalli", "", "");
		StandardUser receiver = new StandardUser("Freund", "", "");

		TextMessage message = new TextMessage(this.textInputArea.getText());

		CommandSendMessage cSendMessage = new CommandSendMessage(sender,
				receiver, message);
		CommandPackage cPackage = this.packageWrapper.wrapPackage(cSendMessage);
		this.connection.send(cPackage);

		this.textInputArea.setText("");
	}
}
